<template>
  <view class="new-or-edit-modal">
    <up-popup v-model:show="show" overlay mode="bottom" touchable maxHeight="'80%'" closeable closeOnClickOverlay
      @close="close" @open="open">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">处理任务</view>
        </view>
        <!-- uview-plus的表单，包含标题，公告内容，单选是否弹窗推送，状态下拉，确认按钮 -->
        <up-form labelPosition="left" :model="formModel" :rules="rules" ref="formRef">
          <up-form-item labelWidth="100" label="处理状态" prop="isTrue">
            <up-radio-group v-model="formModel.isTrue">
              <up-radio label="未处理" name="0"></up-radio>
              <up-radio label="已处理" name="1"></up-radio>
              <up-radio label="驳回" name="2"></up-radio>
            </up-radio-group>
          </up-form-item>
          <!-- 泊位状态 -->
          <up-form-item labelWidth="100" label="泊位状态" prop="berthStatus">
            <up-radio-group v-model="formModel.berthStatus">
              <up-radio label="正常" name="0"></up-radio>
              <up-radio label="异常" name="1"></up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item labelWidth="100" label="备注" prop="remark">
            <up-input v-model="formModel.remark" placeholder="请输入备注" />
          </up-form-item>
          <up-form-item labelWidth="100" label="上传图片" prop="images">
            <up-upload 
              :fileList="formModel.images"
              :maxCount="3" 
              :maxSize="1024 * 1024 * 10" 
              accept="image/*"
              :imageMode="3"
              :uploadText="'上传图片'"
              :previewFullImage="true"
              @afterRead="afterUploadRead"
              @delete="handleDeleteImage"
            />
          </up-form-item>
        </up-form>
      </view>

      <view class="modal-footer">
        <up-button type="primary" @click="submit">确认</up-button>
      </view>
    </up-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { dealErrorBerth, uploadFile } from '@/api';
const formRef = ref(null);
const loading = ref(false);

// 定义组件的 props
const props = defineProps({
  type: {
    type: String,
    default: 'check',
  },
  rowData: {
    type: Object,
    default: () => ({}),
  },
  show: {
    type: Boolean
  }
});

// 定义组件的 emits
const emit = defineEmits(['update:show', 'confirm']);

// 组件名称
defineOptions({
  name: 'CheckModal'
});

// 创建响应式数据  
const show = defineModel<boolean>("show", { default: false });

const formModel = ref(createDefaultModel());
/**
 * 数据模型
 * 是否属实单选框
 * 备注文本框
 * 上传图片
 */
function createDefaultModel() {
  return {
    isTrue: '',
    berthStatus: '',
    remark: '',
    images: [],
  };
}
const rules = reactive({
  isTrue: [{ required: true, message: '请选择是否属实', trigger: 'blur' }],
  berthStatus: [{ required: true, message: '请选择泊位状态', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
  // images: [{ required: false, message: '请上传图片', trigger: 'blur' }],
})

const submit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    
    // 直接使用本地图片URL
    let fileUrl = '';
    if (formModel.value.images && formModel.value.images.length > 0) {
      fileUrl = formModel.value.images.join(',');
    }
    
    console.log('提交的图片URLs:', fileUrl);
    
    // 调用API处理异常泊位
    const { success, msg } = await dealErrorBerth({
      bizCode: props.rowData.id || '',
      isAuthor: formModel.value.isTrue,
      berthStatus: formModel.value.berthStatus,
      dealRemark: formModel.value.remark,
      fileUrl: fileUrl
    });
    
    if (!success) {
      uni.showToast({
        title: msg || '处理失败',
        icon: 'error'
      });
      return;
    }
    
    uni.showToast({
      title: '处理成功',
      icon: 'success'
    });
    
    // 关闭弹窗并通知父组件刷新
    close();
    emit('confirm');
  } catch (error) {
    console.error('处理异常泊位失败', error);
    uni.showToast({
      title: '处理失败，请重试',
      icon: 'error'
    });
  } finally {
    loading.value = false;
  }
}

// 定义方法  
function open(item?: any) {
  if (item) {
    // 如果传入了数据，更新表单数据
    formModel.value = {
      ...createDefaultModel(),
      berthId: item.id || '',
      berthNo: item.berthNo || ''
    };
  }
  show.value = true;
}

function close() {
  // 关闭逻辑，设置 show 为 false  
  show.value = false;
}

// 处理图片上传后的回调
const afterUploadRead = (event: any) => {
  try {
    // 直接使用本地图片URL
    const { file } = event;
    
    // 更新图片数组
    if (!formModel.value.images) {
      formModel.value.images = [];
    }
    
    // 使用本地临时路径
    formModel.value.images.push(file.url || file.path);
    
    console.log('选择的图片:', formModel.value.images);
    
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('添加图片失败', error);
    uni.showToast({
      title: '添加失败',
      icon: 'error'
    });
  }
};

// 处理删除图片
const handleDeleteImage = (index: number) => {
  if (formModel.value.images && formModel.value.images.length > index) {
    formModel.value.images.splice(index, 1);
  }
};
</script>

<style scoped lang="scss">
.new-or-edit-modal {
  .modal-header {
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .modal-content {
    padding: 20rpx;
  }
}
</style>
